/**
 * 应用前台系统设置 migration 的脚本
 * 
 * 使用方法：
 * node scripts/apply-frontend-settings.js
 */

const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

async function applyMigration() {
  try {
    console.log('开始应用前台系统设置...');
    
    // 检查 schema.prisma 是否包含 debian-openssl-1.1.x
    const schemaPath = path.join(__dirname, '../prisma/schema.prisma');
    let schemaContent = fs.readFileSync(schemaPath, 'utf8');
    
    if (!schemaContent.includes('debian-openssl-1.1.x')) {
      console.log('添加 debian-openssl-1.1.x 到 binaryTargets...');
      schemaContent = schemaContent.replace(
        /binaryTargets\s*=\s*\[(.*?)\]/,
        (match, targets) => {
          if (!targets.includes('debian-openssl-1.1.x')) {
            return match.replace(']', ', "debian-openssl-1.1.x"]');
          }
          return match;
        }
      );
      fs.writeFileSync(schemaPath, schemaContent);
      console.log('schema.prisma 已更新');
    }
    
    // 跳过 Prisma 客户端生成，直接执行 SQL
    console.log('直接执行 SQL 语句...');
    
    // 读取 migration 文件内容
    const migrationPath = path.join(__dirname, '../prisma/migrations/20250720000001_add_frontend_settings/migration.sql');
    const migrationSQL = fs.readFileSync(migrationPath, 'utf8');
    
    // 分割 SQL 语句
    const statements = migrationSQL
      .split(';')
      .map(stmt => stmt.trim())
      .filter(stmt => stmt && !stmt.startsWith('--'));
    
    // 使用 mysql 命令行工具执行 SQL
    const dbConfig = {
      host: process.env.DB_HOST || 'hello-beer-db',
      user: process.env.DB_USER || 'root',
      password: process.env.DB_PASSWORD || 'Hello_Beer_2023',
      database: process.env.DB_NAME || 'hello_beer'
    };
    
    console.log('使用 mysql 命令行工具执行 SQL...');
    
    // 创建临时 SQL 文件
    const tempSqlFile = path.join(__dirname, '../temp_migration.sql');
    fs.writeFileSync(tempSqlFile, migrationSQL);
    
    try {
      // 执行 SQL 文件
      const mysqlCmd = `mysql -h${dbConfig.host} -u${dbConfig.user} -p${dbConfig.password} ${dbConfig.database} --skip-ssl < ${tempSqlFile}`;
      execSync(mysqlCmd, { stdio: 'inherit' });
      console.log('SQL 执行成功！');
    } catch (error) {
      console.error('执行 SQL 失败:', error);
      throw error;
    } finally {
      // 删除临时文件
      fs.unlinkSync(tempSqlFile);
    }
    
    console.log('前台系统设置应用成功！');
    
    // 查询设置
    console.log('\n查询已添加的设置:');
    
    const categories = ['frontend.store', 'frontend.receipt', 'frontend.interface'];
    
    for (const category of categories) {
      // 使用单引号代替反引号，或者使用双引号转义
      const query = `SELECT key, value, description FROM SystemSetting WHERE category = '${category}'`;
      // 使用双引号包裹整个命令，避免 shell 解析问题
      const mysqlQueryCmd = `mysql -h${dbConfig.host} -u${dbConfig.user} -p${dbConfig.password} ${dbConfig.database} --skip-ssl -e "${query}" -N`;
      
      console.log(`\n已添加的 ${category} 设置:`);
      try {
        const result = execSync(mysqlQueryCmd).toString();
        console.log(result);
      } catch (error) {
        console.error(`查询 ${category} 设置失败:`, error);
      }
    }
    
  } catch (error) {
    console.error('应用前台系统设置失败:', error);
    process.exit(1);
  }
}

// 执行 migration
applyMigration(); 